package com.wxj.book.controller;

import com.wxj.book.common.Const;
import com.wxj.book.common.ServerResponse;
import com.wxj.book.pojo.Content;
import com.wxj.book.pojo.Receiver;
import com.wxj.book.pojo.User;
import com.wxj.book.service.*;
import com.wxj.book.vo.BorrowVo;
import com.wxj.book.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;


@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserVoService userVoService;
    @Autowired
    private ReceiverService receiverService;
    @Autowired
    private ContentService contentService;
    @Autowired
    private BorrowVoService borrowVoService;

    /**
     * 跳转到个人详情界面
     */
    @RequestMapping("user/info")
    public String loginPage(HttpServletRequest request, Model model) {
        User user = (User) request.getSession(true).getAttribute(Const.CURRENT_USER);
        if (user != null) {
            UserVo userVo = userVoService.getByStuNum(user.getStuNum());
            model.addAttribute("userVo", userVo);
            // 根据专业查询出需要领取的教材
            Content content = contentService.getByMajorId(user.getMajor());
            String s = content.getContent();
            String[] strings = s.split(";");
            List<String> list = new ArrayList<>();
            for (String receiver : strings) {
                list.add(receiver);
            }
            model.addAttribute("list", list);
            // 查询用户的领取记录
            Receiver receiver = receiverService.getByStuNum(user.getStuNum());
            model.addAttribute("receiver", receiver);
            // 查询我的未归还记录
            if (user != null) {
                List<BorrowVo> borrowVos = borrowVoService.getByStuNum(user.getStuNum());
                model.addAttribute("borrowVos", borrowVos);
            }

        }
        return "info";
    }

    /**
     * 用户登录功能 密码默认和学号一样
     */
    @PostMapping("user/login")
    @ResponseBody
    public ServerResponse userLogin(User user, HttpServletRequest request) {
        if (user == null) {
            return ServerResponse.createByErrorMessage("登录失败！");
        }
        User loginUser = userService.login(user);
        if (loginUser == null) {
            return ServerResponse.createByErrorMessage("请检查用户名或密码是否正确！");
        }
        request.getSession(true).setAttribute(Const.CURRENT_USER, loginUser);
        return ServerResponse.createBySuccessMessage("登陆成功！");
    }

}
